package com.coder.oj.common.utils;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.qiniu.cdn.CdnManager;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * 七牛云工具类
 * @author Bosen 2022/12/15 11:26
 **/
public class QiniuUtil {

    private static final String URL = "http://rmx564eft.hn-bkt.clouddn.com";
    // 工作空间名称
    private static final String BUCKET = "coder-oj";
    // 密钥1(AccessKey)
    private static final String AK = "sbYgplY5rOLKuUoYxtT2CoaThocQwxn9cmy2r6l5";
    // 密钥2(SecretKey)
    private static final String SK = "o0RN_6jGS4FjIJXtbyYPzU-mP3kr4XdTv1ueYfsd";
    // 认证信息对象
    private static final Auth AUTH = Auth.create(AK,SK);
    // 存储区域(华东是Region0 华北是Region1 华南是Region2)
    private static final Configuration CONFIGURATION = new Configuration(Zone.zone2());

    /**
     * 上传文件 
     * @author Bosen 2022/12/15 11:34
     **/
    public static void upload(File file, String fileName) {
        String token = AUTH.uploadToken(BUCKET);
        UploadManager uploadManager=new UploadManager(CONFIGURATION);
        try {
            uploadManager.put(file,fileName,token);
        } catch (QiniuException e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除文件 
     * @author Bosen 2022/12/15 11:34
     **/
    public static void delete(String url){
        BucketManager bucketManager = new BucketManager(AUTH, CONFIGURATION);
        try {
            bucketManager.delete(BUCKET, url.replace(URL, ""));
        } catch (QiniuException e) {
            e.printStackTrace();
        }
    }

    /**
     * 刷新文件
     * @author Bosen 2022/12/15 11:34
     **/
    public static void refresh(String url){
        CdnManager c = new CdnManager(AUTH);
        try {
            c.refreshUrls(new String[]{url});
        } catch (QiniuException e) {
            e.printStackTrace();
        }
    }

    /**
     * MultipartFile 转 File
     * @author Bosen 2022/12/15 11:51
     **/
    public static File convert(MultipartFile multipartFile) {
        if(ObjectUtils.isEmpty(multipartFile)) return null;
        File file = null;
        try {
            String originalFilename = multipartFile.getOriginalFilename();
            if(StringUtils.isBlank(originalFilename)) return null;
            String[] filename = originalFilename.split("\\.");
            file = File.createTempFile(filename[0], filename[1]);
            multipartFile.transferTo(file);
            file.deleteOnExit();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }
}
